import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { Mail } from './Mail';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**邮箱属性枚举*/
export const enum E_MailBox {
	/**邮件*/
	MAIL = 0,
	/**接收过运营邮件，删除了，这里依然存在*/
	RECEIVED_ADMIN_MAILS = 1,
	/**枚举数量*/
	EnumCount = 2
}


/**邮箱*/
export class MailBox {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_MAIL_BOX_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_MAIL_BOX_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: MailBox[] = [];

	/**创建入口*/
	public static create(json?: string): MailBox {
		const c = this.POOL.pop() || new MailBox();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**邮件*/
	protected _mail: HashMap<number, Mail> = null;
	/**接收过运营邮件，删除了，这里依然存在*/
	protected _receivedAdminMails: HashMap<number, boolean> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (MailBox.POOL.indexOf(this) === -1) {
			MailBox.POOL.push(this);
		}
	}

	/**设置邮件*/
	public putMail(k: number, v: Mail): Mail {
		const ov = this._mail.put(k, v);
		return ov;
	}


	/**获取邮件*/
	public getMail(k: number) {
		return this._mail.get(k);
	}


	/**删除邮件*/
	public removeMail(k: number, autoDestroy = false): Mail {
		const ov = this._mail.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取邮件映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getMailKeys(): number[] {
		return this._mail.getKeys();
	}


	/**获取邮件映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getMailValues(): Mail[] {
		return this._mail.getValues();
	}


	/**清空邮件映射表*/
	public clearMailMap(autoDestroy = false): void {
		const ks = this._mail.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeMail(ks[i], autoDestroy);
		}
	}


	/**设置接收过运营邮件，删除了，这里依然存在*/
	public putReceivedAdminMails(k: number, v: boolean): boolean {
		const ov = this._receivedAdminMails.put(k, v);
		return ov;
	}


	/**获取接收过运营邮件，删除了，这里依然存在*/
	public getReceivedAdminMails(k: number) {
		return this._receivedAdminMails.get(k);
	}


	/**删除接收过运营邮件，删除了，这里依然存在*/
	public removeReceivedAdminMails(k: number): boolean {
		const ov = this._receivedAdminMails.remove(k);
		return ov;
	}


	/**获取接收过运营邮件，删除了，这里依然存在映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getReceivedAdminMailsKeys(): number[] {
		return this._receivedAdminMails.getKeys();
	}


	/**获取接收过运营邮件，删除了，这里依然存在映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getReceivedAdminMailsValues(): boolean[] {
		return this._receivedAdminMails.getValues();
	}


	/**清空接收过运营邮件，删除了，这里依然存在映射表*/
	public clearReceivedAdminMailsMap(): void {
		this._receivedAdminMails.clear();
	}



	/**通过枚举获取值*/
	public getV(k: E_MailBox): any {
		switch (k) {
			case E_MailBox.MAIL: return this._mail;
			case E_MailBox.RECEIVED_ADMIN_MAILS: return this._receivedAdminMails;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_MailBox, v: any): void {
		switch (k) {
			case E_MailBox.MAIL: this._mail = v; break;
			case E_MailBox.RECEIVED_ADMIN_MAILS: this._receivedAdminMails = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//邮件
		if (this._mail) {
			const list = this._mail.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._mail.clear();
		}
		else {
			this._mail = new HashMap<number, Mail>();
		}
		//接收过运营邮件，删除了，这里依然存在
		if (this._receivedAdminMails) {
			this._receivedAdminMails.clear();
		}
		else {
			this._receivedAdminMails = new HashMap<number, boolean>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._mail.size() > 0) {
			const ks = this._mail.getKeys();
			const vs = this._mail.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.mail = [ks, list];
		}
		if (this._receivedAdminMails.size() > 0) {
			const ks = this._receivedAdminMails.getKeys();
			const vs = this._receivedAdminMails.getValues();
			json.receivedAdminMails = [ks, vs];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.mail) {
			const ks: number[] = json.mail[0] || (json.mail.getKeys ? json.mail.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.mail[1] || (json.mail.getValues ? json.mail.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._mail.put(ks[i], Mail.create(vs[i]));
				}
			}
		}
		if (json.receivedAdminMails) {
			const ks: number[] = json.receivedAdminMails[0];
			const vs: boolean[] = json.receivedAdminMails[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._receivedAdminMails.setKeyAndValueList(ks, vs);
			}
			else if (json.receivedAdminMails.getKeys && json.receivedAdminMails.getValues) {	//结构体
				const ks2 = json.receivedAdminMails.getKeys();
				const vs2 = json.receivedAdminMails.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._receivedAdminMails.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//邮件
		{
			const ks = this._mail.getKeys();
			const vs = this._mail.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeLongNumber(ks[i]);
				vs[i].toBytes(byte);
			}
		}
		//接收过运营邮件，删除了，这里依然存在
		{
			const ks = this._receivedAdminMails.getKeys();
			const vs = this._receivedAdminMails.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeLongNumber(ks[i]);
				byte.writeBool(vs[i]);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//邮件
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readLongNumber();
				const v = Mail.create();
				v.fromBytes(byte);
				this._mail.put(k, v);
			}
		}
		//接收过运营邮件，删除了，这里依然存在
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readLongNumber();
				const v = byte.readBool();
				this._receivedAdminMails.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): MailBox {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = MailBox.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = MailBox.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];

			//邮件
			if (idx === E_MailBox.MAIL) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeMail(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = Mail.create(us[i + 3]);
					const oldv = this.putMail(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getMail(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('MailBox Mail is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			//接收过运营邮件，删除了，这里依然存在
			if (idx === E_MailBox.RECEIVED_ADMIN_MAILS) {
				const k: number = us[i + 1];
				const newv :boolean = us[i + 2];
				const oldv = this.putReceivedAdminMails(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in MailBox with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: MailBox): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//邮件
		{
			const idx = E_MailBox.MAIL;
			const ks1 = this._mail.getKeys();
			const ks2 = other._mail.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getMail(k);
					const oldv = other.getMail(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getMail(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//接收过运营邮件，删除了，这里依然存在
		{
			const idx = E_MailBox.RECEIVED_ADMIN_MAILS;
			const ks1 = this._receivedAdminMails.getKeys();
			const ks2 = other._receivedAdminMails.getKeys();
			const vs1 = this._receivedAdminMails.getValues();
			const vs2 = other._receivedAdminMails.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getReceivedAdminMails(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getReceivedAdminMails(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(MailBox.TOTAL_EVENT_ID, this.getV(0));
	}

}
